package com.daisuxia.back.controller;

import net.sf.json.JSONObject;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.service.ITaskJob;
import com.daisuxia.back.utils.*;
import com.daisuxia.constant.CollectionConstant;
import com.daisuxia.constant.Constant;
import com.daisuxia.payRoute.PayRoute;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.ts.service.ITsOrdersService;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.*;
import com.daisuxia.web.service.*;
import com.daisuxia.web.util.*;

import redis.clients.jedis.JedisCluster;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.daisuxia.web.pojo.BorrowOrder.*;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 还款
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("repayment/")
public class RepaymentController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(RepaymentController.class);

	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	private IReportRepaymentService reportRepaymentService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IRepaymentDetailService repaymentDetailService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IOutOrdersService outOrdersService;
	@Autowired
	private ITaskJob taskJob;
	@Autowired
	private IUserContactsService userContactsService;
	@Autowired
	private IRenewalRecordService renewalRecordService;
	@Autowired
	private IRepaymentAlipayService repaymentAlipayService;
	@Autowired
	private ITsOrdersService tsOrdersService;
	@Autowired
	JedisCluster jedisCluster;
	/*
	 * 待还列表---还款管理---asset_repayment
	 */
	@RequestMapping("getRepaymentPage")
	public String getRepaymentPage(HttpServletRequest request, Integer[] statuses, Model model, String overdueStatus) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			if(null == statuses || statuses.length == 0 || null == statuses[0]){
				// 还款状态为21 23 -11 -20
				statuses = new Integer[]{STATUS_HKZ, STATUS_BFHK, STATUS_YYQ, STATUS_YHZ};
				model.addAttribute("statusesType", "ALL");
			}
			if("S1".equals(overdueStatus)){
				params.put("lateDayStart", "1");
				params.put("lateDayEnd", "10");
			}
			else if("S2".equals(overdueStatus)){
				params.put("lateDayStart", "11");
				params.put("lateDayEnd", "30");
			}
			else if("S3".equals(overdueStatus)){
				params.put("lateDayStart", "31");
				params.put("lateDayEnd", "60");
			}
			params.put("statuses", statuses);
			PageConfig<Repayment> pageConfig = repaymentService.findPage(params);
			model.addAttribute("pm", pageConfig);

		} catch (Exception e) {
			logger.error("getRepaymentPage error", e);
		}
		logger.error(params.toString());
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/repaymentList";
	}
	/*
	 * 已还列表---还款管理--asset_repayment
	 */
	@RequestMapping("getRepaymentedPage")
	public String getRepaymentedPage(HttpServletRequest request, Model model, Integer statuses[]) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			if(null == statuses || statuses.length == 0 || null == statuses[0]){
				// 还款状态为30 34
				statuses = new Integer[] { STATUS_YHK, STATUS_YQYHK };
				model.addAttribute("statusesType", "ALL");
			}
//			atuses=30&statuses=34&myId=209
			params.put("statuses", statuses);
			PageConfig<Repayment> pageConfig = repaymentService.findPage(params);
			model.addAttribute("pm", pageConfig);

		} catch (Exception e) {
			logger.error("getRepaymentedPage error", e);
		}
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/repaymentedList";
	}
	/*
	 * 每日还款单位数据---数据分析--report_repayment
	 */
	@RequestMapping("getReportRepaymentCount")
	public String getReportRepaymentCount(HttpServletRequest request, Model model) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			PageConfig<Repayment> pageConfig = reportRepaymentService.findReportRepaymentCount(params);
			model.addAttribute("pm", pageConfig);
		} catch (Exception e) {
			logger.error("getReportRepaymentCount error", e);
		}
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/reportCount";
	}
	/*
	 * 每日还款金额数据---数据分析--report_repayment
	 */
	@RequestMapping("getReportRepaymentAmount")
	public String getReportRepaymentAmount(HttpServletRequest request, Model model) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			PageConfig<Repayment> pageConfig = reportRepaymentService.findReportRepaymentAmount(params);
			model.addAttribute("pm", pageConfig);
		} catch (Exception e) {
			logger.error("getReportRepaymentAmount error", e);
		}
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/reportAmount";
	}
	/*
	 * 还款逾期统计---数据分析--report_repayment
	 */
	@RequestMapping("getReportRepaymentAll")
	public String getReportRepaymentAll(HttpServletRequest request, Model model) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			PageConfig<Repayment> pageConfig = reportRepaymentService.findReportRepaymentAll(params);
			model.addAttribute("pm", pageConfig);
		} catch (Exception e) {
			logger.error("getReportRepaymentAll error", e);
		}
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/reportAll";
	}
/*
	@RequestMapping("collection/{repaymentId}")
	public void collection(@PathVariable Integer repaymentId){
		try {
			Repayment repayment = repaymentService.selectByPrimaryKey(repaymentId);
			User user = userService.selectCollectionByUserId(repayment.getUserId());
			repaymentService.collection(user, repayment, null, Repayment.OVERDUE_COLLECTION);
		}
		catch (Exception e){
			logger.error("collection error", e);
		}
	}*/


	@RequestMapping("collectionUser")
	public void collectionUser(Integer[] ids){
		try {
			for(Integer id :ids){
				User u = userService.selectCollectionByUserId(id);
				logger.error("collectionUser applying userId = " + u.getId());

				List<Map> loanList = new ArrayList<Map>();

				Map<String, Object> loanMap = new HashMap<String, Object>();

				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("userId", u.getId());
				List<UserContacts> userContacts = userContactsService.selectUserContacts(params);

				// 紧急联系人
				List<Map> mmanUserRelas = new ArrayList<Map>();
				Map<String, String> mmanUserRela = new HashMap<String, String>();
				mmanUserRela.put("id", "");
				mmanUserRela.put("userId", u.getId());
				mmanUserRela.put("contactsKey", "1");
				mmanUserRela.put("relaKey", u.getFristContactRelation());
				mmanUserRela.put("infoName", u.getFirstContactName());
				mmanUserRela.put("infoValue", u.getFirstContactPhone());
				mmanUserRela.put("contactsFlag", "1");
				mmanUserRelas.add(mmanUserRela);

				mmanUserRela = new HashMap<String, String>();
				mmanUserRela.put("id", "");
				mmanUserRela.put("userId", u.getId());
				mmanUserRela.put("contactsKey", "2");
				mmanUserRela.put("relaKey", u.getSecondContactRelation());
				mmanUserRela.put("infoName", u.getSecondContactName());
				mmanUserRela.put("infoValue", u.getSecondContactPhone());
				mmanUserRela.put("contactsFlag", "1");
				mmanUserRelas.add(mmanUserRela);

				for (UserContacts contacts : userContacts) {
					mmanUserRela = new HashMap<String, String>();
					mmanUserRela.put("id", contacts.getId());
					mmanUserRela.put("userId", u.getId());
					mmanUserRela.put("contactsKey", "2");
					mmanUserRela.put("infoName", contacts.getContactName());
					mmanUserRela.put("infoValue", contacts.getContactPhone());
					mmanUserRelas.add(mmanUserRela);
				}

				loanMap.put("mmanUserInfo", u);
				loanMap.put("mmanUserRelas", mmanUserRelas);

				loanList.add(loanMap);

				Map<String, Object> collectionRelevantJson = new HashMap<String, Object>();
				collectionRelevantJson.put("collectionRelevantJson", loanList);

				// 设置参数 可设置多个
				List<NameValuePair> postParams = new ArrayList<NameValuePair>();
				postParams.add(new BasicNameValuePair("collectionRelevantJson", JSONObject.fromObject(collectionRelevantJson).toString()));
				try {
					String result = HttpUtil.getInstance().post(CollectionConstant.getCollectionPath(), postParams);
					JSONObject obj = JSONObject.fromObject(result);
					if (obj.getString("code").equals("0")) {
						logger.error("collectionUser applying success userId = " + id);
					}
				} catch (Exception e) {
					logger.error("collection error", e);
				}
			}

		}
		catch (Exception e){
			logger.error("collection error", e);
		}
	}


	@RequestMapping("overdue1")
	public void overdue1(String ids[],String type){
		try {
//			jedisCluster.set("RENEWAL_" + 3, "3");
//			jedisCluster.set("OVERDUE_" + 3, "3");
//			jedisCluster.set("REPAY_" + 3, "3");
//			jedisCluster.set("WITHHOLD_31dc587e7ea04342ad0860d9a1abe50d", "31dc587e7ea04342ad0860d9a1abe50d");
			/*taskJob.overdue();*/
			logger.error("数据推送开始---------->overdue start");
			if(StringUtils.isNotBlank(type)){
				for(String id : ids){
					try {
						jedisCluster.set(type + "_" + id, "" + id);
						logger.error("collection tuirepay success repaymentId=" + id);
					} catch (Exception e) {
						logger.error("collection tuirepay error repaymentId=" + id, e);
					}
				}

			}
			logger.error("数据推送结束---------->overdue end 共 " + ids.length);
		}
		catch (Exception e){
			logger.error("overdue error", e);
		}
	}

	@RequestMapping("overdue")
	public void overdue(){
		try {
			taskJob.overdue();
		}
		catch (Exception e){
			logger.error("overdue error", e);
		}
	}

	@RequestMapping("withhold")
	public void withhold(){
		try {
			taskJob.withhold();
		}
		catch (Exception e){
			logger.error("withhold error", e);
		}
	}

	public static byte[] getRequestPostBytes(HttpServletRequest request)
			throws IOException {
		int contentLength = request.getContentLength();
		if(contentLength<0){
			return null;
		}
		byte buffer[] = new byte[contentLength];
		for (int i = 0; i < contentLength;) {

			int readlen = request.getInputStream().read(buffer, i,
					contentLength - i);
			if (readlen == -1) {
				break;
			}
			i += readlen;
		}
		return buffer;
	}

	@RequestMapping("alipayRepay")
	public void alipayRepay(HttpServletRequest request, HttpServletResponse response){
		try {
			byte buffer[] = getRequestPostBytes(request);
			String charEncoding = request.getCharacterEncoding();
			if (charEncoding == null) {
				charEncoding = "UTF-8";
			}
			if(null == buffer){
				logger.error("alipayRepay error buffer is null");
				SpringUtils.renderText(response, "fail");
				return;
			}
			String alipays = new String(buffer, charEncoding);
			List<RepaymentAlipay> alipayList = JSONUtil.jsonArrayToBean(alipays, RepaymentAlipay.class);
			for(RepaymentAlipay alipay : alipayList){
				try {
					if(StringUtils.isBlank(alipay.getRemarkPhone())){
						alipay.setRemark("备注手机号为空，无法匹配");
						alipay.setStatus(RepaymentAlipay.STATUS_FAIL);
						repaymentAlipayService.insertSelective(alipay);
					}
					else{
						if(null == alipay.getMoneyAmount() || alipay.getMoneyAmount() < 10){
							alipay.setRemark("支付金额为空或过小");
							alipay.setStatus(RepaymentAlipay.STATUS_FAIL);
							repaymentAlipayService.insertSelective(alipay);
						}
						else{
							Integer id = repaymentService.findUserIdByPhone(alipay.getRemarkPhone());
							if(null == id){
								alipay.setRemark("手机号无法匹配");
								alipay.setStatus(RepaymentAlipay.STATUS_FAIL);
								repaymentAlipayService.insertSelective(alipay);
							}
							else{
								alipay.setStatus(RepaymentAlipay.STATUS_WAIT);
								repaymentAlipayService.insertSelective(alipay);
								alipay = repaymentService.saveByAlipayRepay(alipay,id);
								repaymentAlipayService.updateByPrimaryKeySelective(alipay);
							}
						}
					}
				}
				catch (Exception e){
					logger.error("alipayRepay error orderNo:" + alipay.getAlipayOrderNo() ,e);
				}
			}
			SpringUtils.renderText(response, "ok");
		}
		catch (Exception e){
			logger.error("alipayRepay error" ,e);
			SpringUtils.renderText(response, "fail");
		}
	}


	@RequestMapping("withhold/{repaymentId}")
	public void withhold(@PathVariable Integer repaymentId){
		try {
			Repayment repayment = repaymentService.selectByPrimaryKey(repaymentId);
			logger.error("单个代扣开始 withhold userId = " + repayment.getUserId());
			Repayment re = repaymentService.selectByPrimaryKey(repayment.getId());
			User user = userService.searchByUserid(re.getUserId());
			ServiceResult result = repaymentService.withhold(re, user, Repayment.COLLECTION_WITHHOLD);
			if (result.getCode().equals(ServiceResult.SUCCESS)) {
				RepaymentDetail detail = new RepaymentDetail();
				detail.setUserId(re.getUserId());
				detail.setAssetRepaymentId(re.getId());
				detail.setTrueRepaymentMoney(re.getRepaymentAmount() - re.getRepaymentedAmount());
				detail.setCreatedAt(new Date());
				detail.setOrderId(result.getExt().toString());
				detail.setRepaymentType(RepaymentDetail.TYPE_BANK_CARD_AUTO);
				detail.setRemark("手动任务代扣");
				detail.setUserId(re.getUserId());
				detail.setUpdatedAt(new Date());
				detail.setStatus(RepaymentDetail.STATUS_SUC);
				detail.setAssetOrderId(re.getAssetOrderId());
				repaymentDetailService.insertSelective(detail);
				repaymentService.repay(re, detail);

				// 如果是未逾期的还款，调用提额
				if (re.getLateDay() == 0) {
					user = userService.searchByUserid(re.getUserId());
					logger.error("repay to Mention Money ing ----------------->");
					borrowOrderService.addUserLimit(user);
				}
			}
		} catch (Exception e) {
			logger.error("repay withhold error repaymentId = " + repaymentId, e);
		}
	}

	@RequestMapping("withholdUser/{userId}/{money}")
	public void withhold(@PathVariable Integer userId,@PathVariable Integer money){
		try {
			PayRoute payRoute = new PayRoute(outOrdersService);
			Repayment re = new Repayment();
			re.setRepaymentAmount(money.longValue());
			re.setRepaymentedAmount(0L);
			// 代扣
			String orderNo = GenerateNo.getUUID();
			User user = userService.searchByUserid(re.getUserId());
			UserCardInfo info = userService.findUserBankCard(Integer.parseInt(user.getId()));
			Map map = payRoute.getCutPay(re, user, info, orderNo);
			String retCode = map.get("resp_code").toString();// 返回码
			String ourOrders = map.get("payCutType").toString();//代扣方式
			String signParam = map.get("qbm_signParam").toString();//请求参数
			if ("0000".equals(retCode)) {

				OutOrders outOrders = new OutOrders();
				outOrders.setUserId(user.getId());
				outOrders.setOrderType(ourOrders);
				outOrders.setOrderNo(orderNo);
				outOrders.setAct(OutOrders.ACT_DEBIT);
				outOrders.setReqParams(signParam);
				outOrders.setNotifyParams("");
				outOrders.setReturnParams(map.toString());
				outOrders.setStatus(OutOrders.STATUS_SUC);
				outOrdersService.insert(outOrders);
				logger.error(ourOrders+"_FRONT_DEBIT_RETURN:userId=" + user.getId() + "&orderId=" + outOrders.getId() + "" + "&userId=" + userId + "&code=" + retCode);
				logger.error("代扣单个用户id=" + userId +";金额=" + money);
			}
		} catch (Exception e) {
			logger.error("repay withholdUser error userId = " + userId, e);
		}
	}
/*

	@RequestMapping("withholdUser/{userId}/{money}")
	public void withhold(@PathVariable Integer userId,@PathVariable Integer money){
		try {
			String repayment_no = null;
			String orderNo = GenerateNo.getUUID();
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
			User user = userService.searchByUserid(userId);
			UserCardInfo info = userService.findUserBankCard(userId);
			LianlianGrantSend li = new LianlianGrantSend();
			li.setOid_partner(LianLianConstant.getOidPartner());
			li.setUser_id(user.getId());
			li.setRepayment_no(orderNo);
			li.setRepayment_plan("{\"repaymentPlan\":[{\"date\":\"" + format1.format(new Date()) + "\",\"amount\":\"" + money + "\"}]}");
			li.setSms_param("{\"contract_type\":\"\u6781\u901f\u73b0\u91d1\u4fa0\",\"contact_way\":\"021-56350010\"}");
			li.setNo_agree(info.getAgreeno());
			//加签
			String sginOrigin = LLPayUtil.genSignDataByJavaObject(li);
			li.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
			String signParam = JSONUtil.beanToJson(li);
//			logger.error("LIANLIAN_GRANT_PARAMS:" + signParam);

			String result = HttpUtil.getInstance().postJson(LianLianConstant.getGrantPath(), signParam);
			LianlianGrantRecv grantRecv = JSONUtil.jsonToBean(result, LianlianGrantRecv.class);
			OutOrders outOrders = new OutOrders();
			outOrders.setUserId(user.getId());
			outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
			outOrders.setOrderNo(orderNo);
			outOrders.setAct(OutOrders.ACT_GRANT);
			outOrders.setReqParams(signParam);
			outOrders.setNotifyParams(sginOrigin);
			outOrders.setReturnParams(result);
			outOrders.setStatus(OutOrders.STATUS_SUC);
			outOrdersService.insert(outOrders);
			logger.error("LIANLIAN_FRONT_GRANT_RETURN:userId=" + user.getId() + "&orderId=" + outOrders.getId() + "" + "&userId=" + userId + "&code=" + grantRecv.getRet_code());
			if("0000".equals(grantRecv.getRet_code())){
				repayment_no = grantRecv.getRepayment_no();
			}
			if(StringUtils.isNotBlank(repayment_no)){
				// 代扣
				orderNo = GenerateNo.getUUID();
				LianlianDebitSend ll = new LianlianDebitSend();
				ll.setUser_id(user.getId());
				ll.setNo_order(orderNo);
				ll.setOid_partner(LianLianConstant.getOidPartner());
				ll.setMoney_order("" + money);
				ll.setNotify_url("http://super.xianjinxia.com/repayment/debit-back");
				ll.setValid_order("120");
				ll.setNo_agree(info.getAgreeno());
				ll.setRepayment_no(repayment_no);
				String risk = "{'frms_ware_category':'2010','user_info_mercht_userno':'" + user.getId() + "','user_info_bind_phone':'" + user.getUserPhone()
						+ "','user_info_dt_register':'" + format2.format(user.getCreateTime()) + "','user_info_full_name':'" + user.getRealname() + "','user_info_id_no':'" + user.getIdNumber() + "','user_info_identify_type':'1','user_info_identify_state':'1'}";
				ll.setRisk_item(risk);
				//加签
				sginOrigin = LLPayUtil.genSignDataByJavaObject(ll);
				ll.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
				signParam = JSONUtil.beanToJson(ll);

				result = HttpUtil.getInstance().postJson(LianLianConstant.getDebitPath(), JSONUtil.beanToJson(ll));
				JSONObject jsonObject = JSONObject.fromObject(result);

				outOrders = new OutOrders();
				outOrders.setUserId(user.getId());
				outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
				outOrders.setOrderNo(orderNo);
				outOrders.setAct(OutOrders.ACT_DEBIT);
				outOrders.setReqParams(signParam);
				outOrders.setNotifyParams(sginOrigin);
				outOrders.setReturnParams(result);
				outOrders.setStatus(OutOrders.STATUS_SUC);
				outOrdersService.insert(outOrders);
				logger.error("LIANLIAN_FRONT_DEBIT_RETURN:userId=" + user.getId() + "&orderId=" + outOrders.getId() + "" + "&userId=" + userId + "&code=" + jsonObject.getString("ret_code"));
				if("0000".equals(jsonObject.getString("ret_code"))){
					logger.error("代扣单个用户id=" + userId +";金额=" + money);
				}
			}
		} catch (Exception e) {
			logger.error("repay withholdUser error userId = " + userId, e);
		}
	}

*/

	@RequestMapping("repaySmsRemind")
	public void repaySmsRemind(String amount,String type){
		try {
			if(StringUtils.isNotBlank(amount)){
				SendSmsUtil.sendSmsDiyCL("18516777211", "尊敬的张苏豪，您的" + amount + "借款明日到期，请至APP还款，若到期未还款，平台将自动扣款，请确保尾号9691银行卡资金充足，以免产生逾期。如已还款，请忽略。");
			}
			else if("9".equals(type)){
				taskJob.repaySmsRemind9();
			}
			else{
				taskJob.repaySmsRemind();
			}
		}
		catch (Exception e){
			logger.error("repaySmsRemind error", e);
		}
	}

	@RequestMapping("reportRepaymentTemp")
	public void reportRepaymentTemp() {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String firstRepaymentTime;
			Calendar now = Calendar.getInstance();
			for(int i = 0;i < 40 ; i ++){
				firstRepaymentTime = dateFormat.format(now.getTime());
				if(firstRepaymentTime.equals("2017-01-08")){
					break;
				}
				// 12点后的定时 更新前一日数据 （带逾期信息）
				taskJob.reportRepayment(firstRepaymentTime, i > 0);
				now.add(Calendar.DAY_OF_YEAR,-1);
			}
		}
		catch (Exception e){
			logger.error("reportRepayment error", e);
		}
	}


	@RequestMapping("reportRepayment12")
	public void reportRepayment12() {
		try {
			taskJob.reportRepayment12();
		}
		catch (Exception e){
			logger.error("reportRepayment error", e);
		}
	}

	@RequestMapping("toAgainRepaymentReport")
	public String toAgainRepaymentReport(HttpServletRequest request, Model model) {
		Map<String, String> params =this.getParameters(request);
		model.addAttribute("params", params);
		return "repayment/againRepaymentReport";
	}

	/**
	 * 重新计算统计
	 *
	 * @param nowTime (年月日xxxx-xx-xx)
	 * @param request
	 */
	@RequestMapping("againRepaymentReport")
	public void againRepaymentReport(HttpServletRequest request, HttpServletResponse response, String nowTime) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			if(StringUtils.isNotBlank(nowTime)){
				Calendar now = Calendar.getInstance();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				String firstRepaymentTime = dateFormat.format(now.getTime());
				// 当日刷新 不显示逾期
				if(nowTime.equals(firstRepaymentTime)){
					taskJob.reportRepayment(nowTime, false);
				}
				else{
					now.add(Calendar.DAY_OF_YEAR,-1);
					firstRepaymentTime = dateFormat.format(now.getTime());
					// 昨日
					if(nowTime.equals(firstRepaymentTime)){
						// 昨日刷新 今日12点后 显示逾期
						if(now.get(Calendar.HOUR_OF_DAY) >= 12){
							taskJob.reportRepayment(nowTime, true);
						}
						else{
							taskJob.reportRepayment(nowTime, false);
						}
					}
					else{
						taskJob.reportRepayment(nowTime, true);
					}
				}
			}
		} catch (Exception e) {
			SpringUtils.renderDwzResult(response, false,"服务器异常，请稍后重试！", DwzResult.CALLBACK_CLOSECURRENT);
			logger.error("getUserPage error", e);
		}
		SpringUtils.renderDwzResult(response, true,"操作成功", DwzResult.CALLBACK_CLOSECURRENT,params.get("parentId").toString());
	}

	/**
	 * 刷新当日数据
	 * @param response
	 * @param model
     */
	@RequestMapping("returnRepaymentReport")
	public void returnRepaymentReport(HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			taskJob.reportRepaymentE2();
			SpringUtils.renderDwzResult(response, true, "操作成功", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());
		} catch (Exception e) {
			logger.error("returnRepaymentReport error", e);
		}
	}

	@RequestMapping("reportRepaymentE2")
	public void reportRepaymentE2() {
		try {
			taskJob.reportRepaymentE2();
		}
		catch (Exception e){
			logger.error("reportRepayment error", e);
		}
	}

	/**
	 * 测试连连代扣
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	/*
	 * @RequestMapping("repayTT/{userId}/") public void
	 * repayT(HttpServletRequest request, HttpServletResponse response,
	 * @PathVariable Integer userId) { SimpleDateFormat format1 = new
	 * SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat format2 = new
	 * SimpleDateFormat("yyyyMMddHHmmss"); UserCardInfo info =
	 * userService.findUserBankCard(userId); User user =
	 * userService.searchByUserid(userId);
	 * 
	 * 
	 * 
	 * // 签约 String orderNo = GenerateNo.nextOrdId(); LianlianGrantSend li = new
	 * LianlianGrantSend(); li.setOid_partner(LianLianConstant.getOidPartner());
	 * li.setUser_id(user.getId()); li.setRepayment_no(orderNo);
	 * li.setRepayment_plan("{\"repaymentPlan\":[{\"date\":\"" +
	 * format1.format(new Date()) + "\",\"amount\":\"0.01\"}]}");
	 * li.setSms_param(
	 * "{\"contract_type\":\"\u73b0\u91d1\u4fa0\",\"contact_way\":\"021-60498580\"}"
	 * ); li.setNo_agree(info.getAgreeno()); //加签 String sginOrigin =
	 * LLPayUtil.genSignDataByJavaObject(li);
	 * li.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin)); String
	 * signParam = JSONUtil.beanToJson(li); logger.info("LIANLIAN_GRANT_PARAMS:"
	 * + signParam);
	 * 
	 * String result =
	 * HttpUtil.getInstance().postJson(LianLianConstant.getGrantPath(),
	 * signParam); logger.info("LIANLIAN_GRANT_RETURN:" + result); // JSONObject
	 * jsonObject = JSONObject.fromObject(result); LianlianGrantRecv grantRecv =
	 * JSONUtil.jsonToBean(result, LianlianGrantRecv.class); sginOrigin =
	 * LLPayUtil.genSignDataByJavaObject(grantRecv); //
	 * System.out.println(RSAUtil.sign(
	 * "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSS/DiwdCf/aZsxxcacDnooGph3d2JOj5GXWi+"
	 * + //
	 * "q3gznZauZjkNP8SKl3J2liP0O6rU/Y/29+IUe+GTMhMOFJuZm1htAtKiu5ekW0GlBMWxf4FPkYlQ"
	 * + // "kPE0FtaoMP3gYfh+OwI+fIRrpW3ySn3mScnc6Z700nU/VYrRkfcSCbSnRwIDAQAB",
	 * sginOrigin)); // System.out.println(grantRecv.getSign());
	 * 
	 * 
	 * OutOrders outOrders = new OutOrders(); outOrders.setUserId(user.getId());
	 * outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
	 * outOrders.setOrderNo(orderNo); outOrders.setAct(OutOrders.ACT_GRANT);
	 * outOrders.setReqParams(signParam); outOrders.setReturnParams(result);
	 * outOrders.setStatus(OutOrders.STATUS_SUC);
	 * outOrdersService.insert(outOrders); //
	 * {"api_version":"1.0","no_agree":"2016123021071892"
	 * ,"oid_partner":"201608101001022519"
	 * ,"pay_type":"D","platform":"","repayment_no"
	 * :"20161230171508109221","repayment_plan"
	 * :"{\"repaymentPlan\":[{\"date\":\"2016-12-30\",\"amount\":\"0.01\"}]}"
	 * ,"sign":
	 * "Nwn8hT6+CogezqbbGpdPhXcdZ2RIJDwfnnBRiy7ApJCQtnR3ZbyER4hc1xRvaJcG0qlVgxO302jThx4/sxyE0MGq9rFrfI8oDpYJ6kNDaFiSViOlnkE8YJb+d46pDHY/P1UhDyIuiDZko9oe1en8wdNdV2IGqOCPHlsC/tAvJz4="
	 * ,"sign_type":"RSA","sms_param":
	 * "{\"contract_type\":\"现金侠\",\"contact_way\":\"021-60498580\"}"
	 * ,"user_id":"1111"} //
	 * {"ret_code":"0000","ret_msg":"交易成功","sign_type":"RSA","sign":
	 * "Avtv/NU/HaIsX/iRD/REfVIIocOm8zCi9os9Vpx6fAswSHeZFWcsDTy+IdtC5ptT9n2f26rStvoU7eNti/lVFNE/QwTpC42HJVhY/6CPYDm3+B13xrobtPZ2qS+u9Lkil6klWIP+ikDvblXPud03DqhrfH92jKq2WMgEyoweLYQ="
	 * ,"correlationID":"1bba5d74-a13e-4d3f-928c-43c18f6d4911","token":
	 * "61C979F1C0112EB0F36A1CCEDF13E8D4"
	 * ,"oid_partner":"201608101001022519","no_agree"
	 * :"2016123021071892","repayment_no":"20161230171508109221"}
	 * 
	 * 
	 * // 代扣 orderNo = GenerateNo.nextOrdId(); LianlianDebitSend ll = new
	 * LianlianDebitSend(); // li.setPlatform("180.173.0.188");
	 * ll.setUser_id(user.getId()); ll.setNo_order(orderNo);
	 * ll.setOid_partner(LianLianConstant.getOidPartner());
	 * ll.setMoney_order("0.01");
	 * ll.setNotify_url(RequestUtils.getRequestPath(null) +
	 * "/repayment/debit-back"); ll.setValid_order("10");
	 * ll.setNo_agree(info.getAgreeno());
	 * ll.setRepayment_no(grantRecv.getRepayment_no()); String risk =
	 * "{'frms_ware_category':'2010','user_info_mercht_userno':'" + userId +
	 * "','user_info_bind_phone':'" + user.getUserPhone() +
	 * "','user_info_dt_register':'" + format2.format(user.getCreateTime()) +
	 * "','user_info_full_name':'" + user.getRealname() +
	 * "','user_info_id_no':'" + user.getIdNumber() +
	 * "','user_info_identify_type':'1','user_info_identify_state':'1'}";
	 * ll.setRisk_item(risk); //加签 sginOrigin =
	 * LLPayUtil.genSignDataByJavaObject(ll);
	 * ll.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
	 * signParam = JSONUtil.beanToJson(ll); logger.info("LIANLIAN_DEBIT_PARAMS:"
	 * + signParam);
	 * 
	 * result = HttpUtil.getInstance().postJson(LianLianConstant.getDebitPath(),
	 * JSONUtil.beanToJson(ll)); logger.info("LIANLIAN_DEBIT_RETURN:" + result);
	 * 
	 * outOrders = new OutOrders(); outOrders.setUserId(user.getId());
	 * outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
	 * outOrders.setOrderNo(orderNo); outOrders.setAct(OutOrders.ACT_DEBIT);
	 * outOrders.setReqParams(signParam); outOrders.setReturnParams(result);
	 * outOrders.setStatus(OutOrders.STATUS_SUC);
	 * outOrdersService.insert(outOrders); }
	 */

	/**
	 * 还款
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("repay")
	public String repay(HttpServletRequest request, HttpServletResponse response, Model model, RepaymentDetail detail) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		BackUser backUser = this.loginAdminUser(request);
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				if (null != detail.getAssetRepaymentId()) {
					// 更新的页面跳转
					Repayment repayment = repaymentService.selectByPrimaryKey(detail.getAssetRepaymentId());
					model.addAttribute("remainMoney", (repayment.getRepaymentAmount() - repayment.getRepaymentedAmount()) / 100.00);
					model.addAttribute("assetRepaymentId", detail.getAssetRepaymentId());
				}
				url = "repayment/repay";
			} else {
				if (null == detail.getAssetRepaymentId()) {
					erroMsg = "请选择一条还款数据！";
				} else {
					Repayment repayment = repaymentService.selectByPrimaryKey(detail.getAssetRepaymentId());
					if (null == repayment) {
						erroMsg = "该还款数据无效！";
					} else if (!BorrowOrder.STATUS_HKZ.equals(repayment.getStatus()) && !BorrowOrder.STATUS_BFHK.equals(repayment.getStatus()) && !BorrowOrder.STATUS_YYQ.equals(repayment.getStatus()) && !BorrowOrder.STATUS_YHZ.equals(repayment.getStatus())) {
						erroMsg = "本条数据不能还款！";
					} else {
						detail.setAdminUsername(backUser.getUserAccount());
						detail.setUserId(repayment.getUserId());
						detail.setUpdatedAt(new Date());
						detail.setStatus(RepaymentDetail.STATUS_SUC);
						detail.setAssetOrderId(repayment.getAssetOrderId());
						repaymentDetailService.insertSelective(detail);
						repaymentService.repay(repayment, detail);
						tsOrdersService.sendBorrowStatus(repayment.getAssetOrderId());
						// 如果是未逾期的还款，调用提额
						if (repayment.getLateDay() == 0) {
							User user = userService.searchByUserid(repayment.getUserId());
							logger.info("repay to Mention Money ing ----------------->");
							borrowOrderService.addUserLimit(user);
						}
					}
				}
				SpringUtils.renderDwzResult(response, null == erroMsg, null == erroMsg ? "操作成功！" : erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
		} catch (Exception e) {
			erroMsg = "服务器异常，请稍后重试！";
			SpringUtils.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			logger.error("添加权限信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}


	/**
	 * 续期
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("renewal")
	public String renewal(HttpServletRequest request, HttpServletResponse response, Model model, RenewalRecord rr,String createdAtStr) {
		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		BackUser backUser = this.loginAdminUser(request);
		try {
			if ("toJsp".equals(String.valueOf(params.get("type")))) {
				Repayment re = repaymentService.selectByPrimaryKey(rr.getAssetRepaymentId());
				BorrowOrder bo = borrowOrderService.findOneBorrow(re.getAssetOrderId());
				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
				// 续期费
				String renewalFee = keys.get("renewal_fee");
				// 待还总金额
				Long waitRepay = re.getRepaymentAmount() - re.getRepaymentedAmount();
				// 待还滞纳金
				Long waitLate = Long.parseLong(String.valueOf(re.getPlanLateFee() - re.getTrueLateFee()));
				// 待还本金
				Long waitAmount = waitRepay - waitLate;
				// 服务费
				Integer loanApr = bo.getMoneyAmount() * bo.getApr() / 10000;   //服务费
				Long allCount = waitLate + loanApr + Long.parseLong(renewalFee);

				model.addAttribute("waitAmount", waitAmount);
				model.addAttribute("loanApr", loanApr);
				model.addAttribute("renewalFee", renewalFee);
				model.addAttribute("waitLate", waitLate);
				model.addAttribute("allCount", allCount);
				model.addAttribute("assetRepaymentId", rr.getAssetRepaymentId());
				url = "repayment/renewal";
			} else {
				logger.error("repayment renewal repaymentId:" + rr.getAssetRepaymentId());
				Repayment repayment = repaymentService.selectByPrimaryKey(rr.getAssetRepaymentId());
				BorrowOrder bo = borrowOrderService.findOneBorrow(repayment.getAssetOrderId());
				// 待还总金额
				Long waitRepay = repayment.getRepaymentAmount() - repayment.getRepaymentedAmount();
				// 待还滞纳金
				Long waitLate = Long.parseLong(String.valueOf(repayment.getPlanLateFee() - repayment.getTrueLateFee()));
				// 待还本金
				Long waitAmount = waitRepay - waitLate;
				// 续期信息
				rr.setUserId(repayment.getUserId());
//				rr.setAssetRepaymentId(re.getId());
				rr.setRepaymentPrincipal(waitAmount);
//				rr.setSumFee(allCount);
//				rr.setRepaymentInterest((long)loanApr);
//				rr.setPlanLateFee(waitLate.intValue());
//				rr.setRenewalFee(Integer.valueOf(renewalFee));
				rr.setOldRepaymentTime(repayment.getRepaymentTime());
				rr.setRenewalDay(bo.getLoanTerm());
				rr.setStatus(RenewalRecord.STATUS_SUCC);
				rr.setRemark(rr.getRemark() + "  操作员:" + backUser.getUserAccount());
				rr.setMoneyAmount(repayment.getRepaymentPrincipal() + repayment.getRepaymentInterest());
				rr.setRepaymentTime(DateUtil.addDay(repayment.getRepaymentTime(), bo.getLoanTerm()));
				renewalRecordService.insertSelective(rr);


				BorrowOrder borrowOrder = new BorrowOrder();
				borrowOrder.setId(repayment.getAssetOrderId());
				borrowOrder.setStatus(BorrowOrder.STATUS_HKZ);
				borrowOrderService.updateById(borrowOrder);

				Repayment re = new Repayment();
				// 如果申请续期成功
				re.setId(repayment.getId());
				re.setRepaymentAmount(repayment.getRepaymentPrincipal() + repayment.getRepaymentInterest() - repayment.getRepaymentedAmount());
				re.setPlanLateFee(0);
				re.setTrueLateFee(0);
				// 还款日期 延后 （逾期天数+续期天数）
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if(StringUtils.isNotBlank(createdAtStr)){
					try {
						Date createdAt = dateFormat.parse(createdAtStr);
						re.setRepaymentTime(DateUtil.addDay(createdAt,  rr.getRenewalDay()));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				else{
					re.setRepaymentTime(DateUtil.addDay(repayment.getRepaymentTime(), repayment.getLateDay() + rr.getRenewalDay()));
				}
				re.setLateFeeStartTime(null);
				re.setInterestUpdateTime(null);
				re.setLateDay(0);
				re.setRenewalCount(repayment.getRenewalCount() + 1);
				re.setStatus(BorrowOrder.STATUS_HKZ);
				re.setCollection(Repayment.COLLECTION_NO);
				repaymentService.updateRenewalByPrimaryKey(re);
				tsOrdersService.sendBorrowStatus(repayment.getAssetOrderId());
				// 如果是已逾期的续期（调用催收同步）
				if (repayment.getStatus().equals(BorrowOrder.STATUS_YYQ)) {
//					repayment = repaymentService.selectByPrimaryKey(rr.getAssetRepaymentId());
//					User user = userService.selectCollectionByUserId(repayment.getUserId());
					try {
						jedisCluster.set("RENEWAL_" + re.getId(), ""+re.getId());
						logger.error("collection renewal success RENEWAL_" + re.getId() + " value=" + jedisCluster.get("REPAY_" + re.getId()));
					} catch (Exception e) {
						logger.error("collection renewal error repaymentId=" + re.getId(), e);
					}
//					repaymentService.collection(user, repayment, null, Repayment.OVERDUE_COLLECTION);
				}

				SpringUtils.renderDwzResult(response, true, "操作成功！", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
		} catch (Exception e) {
			erroMsg = "服务器异常，请稍后重试！";
			SpringUtils.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			logger.error("添加权限信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}


	/**
	 * 导出待还Excel
	 */
	@RequestMapping("toDHExcel")
	public void toDHExcel(HttpServletRequest request, HttpServletResponse response, Integer statuses[], String overdueStatus) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			if(null == statuses || statuses.length == 0 || null == statuses[0]){
				statuses = new Integer[]{STATUS_HKZ, STATUS_BFHK, STATUS_YYQ, STATUS_YHZ};
			}
			if("S1".equals(overdueStatus)){
				params.put("lateDayStart", "1");
				params.put("lateDayEnd", "10");
			}
			else if("S2".equals(overdueStatus)){
				params.put("lateDayStart", "11");
				params.put("lateDayEnd", "30");
			}
			else if("S3".equals(overdueStatus)){
				params.put("lateDayStart", "31");
				params.put("lateDayEnd", "60");
			}
			params.put("statuses", statuses);
			SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKBH,
					BorrowOrder.STATUS_FKSB));
			int totalPageNum = repaymentService.findParamsCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}

			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "待还列表.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);

			String[] titles = { "序号", "姓名", "手机号", "是否是老用户", "借款到账金额", "服务费", "总需要还款金额", "已还金额", "放款时间", "预期还款时间", "逾期天数", "状态"};
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<Repayment> pm = repaymentService.findPage(params);
				List<Repayment> repaymentList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (Repayment repayment : repaymentList) {
					Object[] conList = new Object[titles.length];
					conList[0] = repayment.getId();
					conList[1] = repayment.getRealname();
					conList[2] = repayment.getUserPhone();
					if(0 == (repayment.getCustomerType())){
						conList[3] = "新用户";
					}
					else{
						conList[3] = "老用户";
					}
					conList[4] = repayment.getRepaymentPrincipal() / 100.00;
					conList[5] = repayment.getRepaymentInterest() / 100.00;
					conList[6] = repayment.getRepaymentAmount() / 100.00;
					conList[7] = repayment.getRepaymentedAmount() / 100.00;
					conList[8] = sfd.format(repayment.getCreditRepaymentTime());
					conList[9] = sfd.format(repayment.getRepaymentTime());
					conList[10] = repayment.getLateDay();
					conList[11] = BorrowOrder.borrowStatusMap.get(repayment.getStatus());
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "待还列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}
//		backBorrowOrder/toFKExcel
	}

	/**
	 * 导出还款Excel
	 */
	@RequestMapping("toYHExcel")
	public void toYHExcel(HttpServletRequest request, HttpServletResponse response, Integer statuses[]) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			if(null == statuses || statuses.length == 0 || null == statuses[0]){
				statuses = new Integer[] { STATUS_YHK, STATUS_YQYHK };
			}
			params.put("statuses", statuses);
			SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKBH,
					BorrowOrder.STATUS_FKSB));
			int totalPageNum = repaymentService.findParamsCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}

			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "还款列表.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);

			String[] titles = { "序号", "姓名", "手机号", "是否是老用户", "借款到账金额", "服务费", "总需要还款金额", "已还金额", "放款时间", "还款时间", "预期还款时间", "状态"};
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<Repayment> pm = repaymentService.findPage(params);
				List<Repayment> repaymentList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (Repayment repayment : repaymentList) {
					Object[] conList = new Object[titles.length];
					conList[0] = repayment.getId();
					conList[1] = repayment.getRealname();
					conList[2] = repayment.getUserPhone();
					if(0 == (repayment.getCustomerType())){
						conList[3] = "新用户";
					}
					else{
						conList[3] = "老用户";
					}
					conList[4] = repayment.getRepaymentPrincipal() / 100.00;
					conList[5] = repayment.getRepaymentInterest() / 100.00;
					conList[6] = repayment.getRepaymentAmount() / 100.00;
					conList[7] = repayment.getRepaymentedAmount() / 100.00;
					conList[8] = sfd.format(repayment.getCreditRepaymentTime());
					conList[9] = sfd.format(repayment.getRepaymentRealTime());
					conList[10] = sfd.format(repayment.getRepaymentTime());
					conList[11] = BorrowOrder.borrowStatusMap.get(repayment.getStatus());
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "还款列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}
	/**
	 * 还款对账
	 * @param request
	 * @param statuses
	 * @param model
	 * @param overdueStatus
	 * @return
	 */
	@RequestMapping("getRepaymentCheckPage")
	public String getRepaymentCheckPage(HttpServletRequest request, Integer[] statuses, Model model, String overdueStatus) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			if(null == params.get("createdAt")){
				 params.put("createdAt", DateUtil.getDateFormat("yyyy-MM-dd"));
				 params.put("createdAtEnd", DateUtil.getDateFormat("yyyy-MM-dd"));
				
			}
			PageConfig<RepaymentChecking> pageConfig = repaymentDetailService.checkRepayment(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params",params);

		} catch (Exception e) {
			logger.error("getRepaymentCheckPage error", e);
		}
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/repaymentCheckList";
	}
	
	/**
	 * 续期对账
	 * @param request
	 * @param statuses
	 * @param model
	 * @param overdueStatus
	 * @return
	 */
	@RequestMapping("getRenewalCheckPage")
	public String getRenewalCheckPage(HttpServletRequest request, Integer[] statuses, Model model, String overdueStatus) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			if(null == params.get("orderTime")){
				 params.put("orderTime", DateUtil.getDateFormat("yyyy-MM-dd"));
				 params.put("orderTimeEnd", DateUtil.getDateFormat("yyyy-MM-dd"));
				
			}
			PageConfig<RepaymentChecking> pageConfig = repaymentDetailService.checkRenewal(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params",params);

		} catch (Exception e) {
			logger.error("getRepaymentCheckPage error", e);
		}
		model.addAttribute("params", params);// 用于搜索框保留值
		return "repayment/renewalCheckList";
	}
	
	
	/**
	 * 导出还款对账Excel
	 */
	@RequestMapping("toHkExcel")
	public void toHkDZExcel(HttpServletRequest request, HttpServletResponse response, Integer statuses[]) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			int totalPageNum = repaymentDetailService.checkRepaymentCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			if(null == params.get("createdAt")){
				 params.put("createdAt", DateUtil.getDateFormat("yyyy-MM-dd"));
				 params.put("createdAtEnd", DateUtil.getDateFormat("yyyy-MM-dd"));
				
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "还款对账列表.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);

			String[] titles = { "序号", "用户ID","姓名", "手机号", "还款Id", "总还款金额", "已还款金额", "实还金额", "退款金额","订单Id", "还款方式", "还款状态", "还款详情状态", "还款时间","放款账户"};
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<RepaymentChecking> pm = repaymentDetailService.checkRepayment(params);
				List<RepaymentChecking> repaymentList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				int j = 1;
				for (RepaymentChecking rc : repaymentList) {
					Object[] conList = new Object[titles.length];
					conList[0] = j;
					conList[1] = rc.getUserId();
					conList[2] = rc.getRealname();
					conList[3] = rc.getPhone();
					conList[4] = rc.getReapymentId();
					conList[5] = rc.getRepaymentAmount() / 100.00;
					conList[6] = rc.getRepaymentedAmount() / 100.00;
					conList[7] = rc.getTrueRepaymentMoney() / 100.00;
					double returnMoney = 0;
					try {
						if(StringUtils.isNotBlank(rc.getBackOrderId())){
							returnMoney = Long.parseLong(rc.getBackOrderId()) / 100.00;
						}
					} catch (Exception e) {
						
					}
					conList[8] = returnMoney;
					conList[9] = rc.getOrderId();
					conList[10] = RepaymentDetail.REPAY_TYPE.get(rc.getRepaymentType());
					conList[11] = BorrowOrder.borrowStatusMap.get(rc.getReapymentStatus());
					String detailStatus = RepaymentChecking.REPAYMENT_STATUS.get(rc.getStatus());
					if(StringUtils.isBlank(detailStatus)){
						detailStatus = RepaymentChecking.BACK_REPAY_STATUS.get(rc.getStatus());
					}
					conList[12] = detailStatus;
					conList[13] =  sfd.format(rc.getCreatedAt());
					conList[14] =  BorrowOrder.LOAN_ACCOUNTMap.get(rc.getCapitalType());
					contents.add(conList);
					j++;
				}
				ExcelUtil.buildExcel(workbook, "还款对账列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}
	
	/**
	 * 导出续期对账Excel
	 */
	@RequestMapping("toXQExcel")
	public void toXQDZExcel(HttpServletRequest request, HttpServletResponse response, Integer statuses[]) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int size = 50000;
			params.put(Constant.PAGE_SIZE, size);
			int totalPageNum = repaymentDetailService.checkRenewalCount(params);
			int total = 0;
			if (totalPageNum > 0) {
				if (totalPageNum % size > 0) {
					total = totalPageNum / size + 1;
				} else {
					total = totalPageNum / size;
				}
			}
			if(null == params.get("orderTime")){
				 params.put("orderTime", DateUtil.getDateFormat("yyyy-MM-dd"));
				 params.put("orderTimeEnd", DateUtil.getDateFormat("yyyy-MM-dd"));
				
			}
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "续期对账列表.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);

			String[] titles = { "序号", "用户ID", "姓名", "手机号", "还款Id", "订单ID", "总还款金额", "已还款金额", "服务费", "续期天数", "续期费","退款金额", "续期前应还时间", "续期后应还时间","续期方式","续期时间","放款账户"};
			for (int i = 1; i <= total; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<RepaymentChecking> pm = repaymentDetailService.checkRenewal(params);
				List<RepaymentChecking> checkList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				int j = 1;
				for (RepaymentChecking rc : checkList) {
					Object[] conList = new Object[titles.length];
					conList[0] = j;
					conList[1] = rc.getUserId();
					conList[2] = rc.getRealname();
					conList[3] = rc.getPhone();
					conList[4] = rc.getReapymentId();
					conList[5] = rc.getOrderId();
					conList[6] = rc.getRepaymentAmount() / 100.00;
					conList[7] = rc.getRepaymentedAmount() / 100.00;
					conList[8] = rc.getRepaymentInterest() / 100.00;
					conList[9] = rc.getRenewalDay();
					conList[10] = rc.getTrueRepaymentMoney() / 100.00;
					conList[11] = rc.getReturnMoney() / 100.00;
					conList[12] = sfd.format(rc.getOldRepaymentTime());
					conList[13] = sfd.format(rc.getRepaymentTime());
					String renewalType = "未知渠道";
					if(rc.getRenewalType() == 1){
						renewalType = "富友";
					}else if(rc.getRenewalType() == 2){
						renewalType = "支付宝";
					}
					conList[14] = renewalType;
					conList[15] =  sfd.format(rc.getOrderTime());
					conList[16] =  BorrowOrder.LOAN_ACCOUNTMap.get(rc.getCapitalType());
					contents.add(conList);
					j++;
				}
				ExcelUtil.buildExcel(workbook, "续期对账列表", titles, contents, i, pm.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}
	
	
}
